package com.heima.search.service.impl;

import com.heima.common.search.EsDataIndexConstants;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    EsService esService;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //1 参数检查
        String searchWords = dto.getSearchWords();
        if (StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 保存用户搜索历史记录
        // 获取当前用户id(保存用户是异步调用,另起线程 无法从threadLocal中获取UserId)
        Integer userId = AppThreadLocalUtils.getUser().getId();
        if (userId != null) dto.setEntryId(userId);
        apUserSearchService.insert(dto);
        //2 构建查询条件执行查询
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建查询条件和过滤等
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键词查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", searchWords));
        //查询小于minDate的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //分页并按照发布时间降序
        sourceBuilder.from(0).size(dto.getPageSize()).sort("publishTime", SortOrder.DESC);
        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>");
        //聚合查询条件
        sourceBuilder.highlighter(highlightBuilder).query(boolQueryBuilder);
        PageResponseResult searchResult = esService.search(sourceBuilder, SearchArticleVO.class, EsDataIndexConstants.ARTICLE_INDEX_NAME);
        //4 返回结果 staticUrl 需要拼接 minIO文章服务器的前缀路径
        List<SearchArticleVO> list = (List<SearchArticleVO>) searchResult.getData();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SearchArticleVO searchArticleVo : list) {
                searchArticleVo.setStaticUrl(readPath + searchArticleVo.getStaticUrl());
            }
        }
        return searchResult;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article, EsDataIndexConstants.ARTICLE_INDEX_NAME);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(EsDataIndexConstants.ARTICLE_INDEX_NAME, articleId);
    }
}
